package com.ctsi.crm.sync.controller;

import com.ctsi.auth.integration.RSAUtil;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.commons.util.json.JsonUtil;
import com.ctsi.commons.util.response.Page;
import com.ctsi.crm.sync.domain.CustInfo;
import com.ctsi.crm.sync.domain.RegionInfo;
import com.ctsi.crm.sync.entity.CrmSyncEntity;
import com.ctsi.crm.sync.params.SyncParams;
import com.ctsi.crm.sync.service.SyncService;
import com.ctsi.framework.common.response.UnifiedResponse;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
public class CrmSyncController {

    private static Logger logger = LoggerFactory.getLogger(CrmSyncController.class);

    @Autowired
    private SyncService syncService;

    private String pub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaf5TwRy/SsZx5LPCkcvvyfL4V6A829dXdQx60hTRsctUiBYQrcB+70OlUOkmpYh/RgjMICgSUOV+Dqol+1bh2i7VknHSlyIMa+QVB/nJs6EmU03LEjEbVUksg6SPsI2ZhNRzAYWam/+xN/r6hlAFE5eAzEdz3teWxnIt/IMPZ/QIDAQAB";
//    私钥：/nMIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJp/lPBHL9KxnHks8KRy+/J8vhXoDzb11d1DHrSFNGxy1SIFhCtwH7vQ6VQ6SaliH9GCMwgKBJQ5X4OqiX7VuHaLtWScdKXIgxr5BUH+cmzoSZTTcsSMRtVSSyDpI+wjZmE1HMBhZqb/7E3+vqGUAUTl4DMR3Pe15bGci38gw9n9AgMBAAECgYBJ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uBo4DQYke3NkZlS4OKhKIhr9zglxRIZEbUCQQCrrBgC2J0FW+X0cGIDwkCzEOgWmZa/mPqcGfB4mVxVMHtTrIE+B3E4u5hWMCOYgAGrPr44UlU3njD5gPogEnQpAkB1RyZAht83HpFvyR53pFshiSBzqkCfPqEMEJg4YHl8kOdf2W7pCLVmINzoiA1Y4UkZpH/HvcPVVihdk5Ry9wH1AkEApzANnk/48+wg0mLUgdafjgSMEt53WpcQkhANClZI/sodgUrB/3feAyNnY6C0OeOIPI75T/6W8XiFN6gtcCioqQJAQ5vRqqMnZKRM9KzVB3ARtzsA3RdLi4L5jffM9S5t1WfJdSXLmuMPLOjHvV8uQiTiLbRLQaDi5VET7TzgopKxLQ==";

    @PostMapping("/crm-sync/sync")
    public UnifiedResponse<String> findSync(@RequestBody SyncParams params) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String custId = params.getCrmCustIds();
        List<String> custIds = Stream.of(custId.split(",")).collect(Collectors.toList());
        String crmCustNameLike = params.getCrmCustNameLike();
        String applyUserNameLike = params.getApplyUserNameLike();
        if (UtilValidate.isNotEmpty(crmCustNameLike)) {
            crmCustNameLike = "%" + crmCustNameLike+"%";
            map.put("crmCustNameLike",crmCustNameLike);
        }
        if (UtilValidate.isNotEmpty(applyUserNameLike)) {
            applyUserNameLike = "%" + applyUserNameLike+"%";
            map.put("applyUserNameLike",applyUserNameLike);
        }
        map.put("custIds",custIds);
        Page<CrmSyncEntity> result = syncService.queryList(map, params.getStart(), params.getPageSize());
        String json = JsonUtil.toJson(result);
//         String ency = Base64.encodeBase64String(RSAUtil.encryptByPrivateKey(json.getBytes(), Base64Utils.decodeFromString(pk))) ;
        String ency = Base64.encodeBase64String(RSAUtil.encryptByPrivateKeySegment(json.getBytes("UTF-8"), Base64Utils.decodeFromString(pk)));
//        logger.error("{}", new String(RSAUtil.decryptByPublicKeySegment(Base64Utils.decodeFromString(ency), Base64Utils.decodeFromString(pub)),"utf-8"));
        return UnifiedResponse.ok(ency);
    }


    /**
     * 地域接口
     */
    @PostMapping("/crm-sync/regions")
    public UnifiedResponse<List<RegionInfo>> regionInfos(){
        return UnifiedResponse.ok(syncService.syncRegion());
    }

    /**
     * 客户接口
     */
    @PostMapping("/crm-sync/custs")
    public UnifiedResponse<List<CustInfo>> custInfos(@RequestParam("regionId") String regionId,
                                               @RequestParam("certNum") String certNum){
        if (UtilValidate.isEmpty(regionId) || UtilValidate.isEmpty(certNum)) {
            UnifiedResponse.ok(Collections.emptyList());
        }
        return UnifiedResponse.ok(syncService.syncCust(regionId,certNum));
    }
}
